import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:vamos/core/index.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:math';
import '../../core/models/question_entity.dart';
import '../../core/widgets/report_dialog.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';

/// AI对话界面
class VamosAIChatInterface extends StatefulWidget {
  final QuestionEntity question;
  final String initialMessage;

  const VamosAIChatInterface({
    Key? key,
    required this.question,
    this.initialMessage = '',
  }) : super(key: key);

  @override
  State<VamosAIChatInterface> createState() => _VamosAIChatInterfaceState();
}

class _VamosAIChatInterfaceState extends State<VamosAIChatInterface> {
  late ReduxUserManager _userManager;
  final TextEditingController _messageController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  final List<AIChatMessage> _messages = [];
  String? _conversationId;
  bool _isLoading = false;
  String _sessionId = '';

  @override
  void initState() {
    super.initState();
    _userManager = serviceLocator<ReduxUserManager>();
    _sessionId = _generateSessionId();

    // 如果有初始消息，自动发送
    if (widget.initialMessage.isNotEmpty) {
      _sendMessage(widget.initialMessage);
    }
  }

  @override
  void dispose() {
    _messageController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  /// 生成会话ID
  String _generateSessionId() {
    final timestamp = DateTime.now().millisecondsSinceEpoch;
    final random = Random().nextInt(999999999); // 9位随机数
    return '${timestamp}_${random.toString().padLeft(9, '0')}';
  }

  /// 发送消息
  void _sendMessage(String content) async {
    if (content.trim().isEmpty) return;

    // 添加用户消息
    final userMessage = AIChatMessage(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      content: content,
      isUser: true,
      timestamp: DateTime.now(),
    );

    setState(() {
      _messages.add(userMessage);
      _isLoading = true;
    });

    // 滚动到底部
    _scrollToBottom();

    try {
      // 调用AI接口
      final response = await _callAIAPI(content);

      if (response != null) {
        // 添加AI回复
        final aiMessage = AIChatMessage(
          id: DateTime.now().millisecondsSinceEpoch.toString(),
          content: response['answer'] ?? '',
          isUser: false,
          timestamp: DateTime.now(),
        );

        setState(() {
          _messages.add(aiMessage);
          _conversationId = response['conversation_id'];
        });
      } else {
        // 显示错误消息
        final errorMessage = AIChatMessage(
          id: DateTime.now().millisecondsSinceEpoch.toString(),
          content: 'Sorry, I encountered an error. Please try again.',
          isUser: false,
          timestamp: DateTime.now(),
        );

        setState(() {
          _messages.add(errorMessage);
        });
      }
    } catch (e) {
      // 显示错误消息
      final errorMessage = AIChatMessage(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        content: 'Sorry, I encountered an error. Please try again.',
        isUser: false,
        timestamp: DateTime.now(),
      );

      setState(() {
        _messages.add(errorMessage);
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
      _scrollToBottom();
    }
  }

  /// 调用AI接口
  Future<Map<String, dynamic>?> _callAIAPI(String content) async {
    try {
      final url = Uri.parse('https://api.wiseaii.com/wiseai/v1/chat');

      final Map<String, dynamic> requestBody = {
        'bundle_id': 'com.vamos.ios', // 替换为你的bundle_id
        'session_id': _sessionId,
        'content_type': 'text',
        'content': content,
      };

      // 如果有conversation_id，添加到请求中
      if (_conversationId != null) {
        requestBody['conversation_id'] = _conversationId;
      }

      final response = await http.post(
        url,
        headers: {'Content-Type': 'application/json'},
        body: json.encode(requestBody),
      );

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        if (data['code'] == 1003) {
          return data['data'];
        }
      }

      return null;
    } catch (e) {
      print('AI API调用失败: $e');
      return null;
    }
  }

  /// 滚动到底部
  void _scrollToBottom() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  /// 检查用户是否登录
  bool _isUserLoggedIn() {
    return _userManager.getCurrentUser() != null;
  }

  /// 获取用户头像
  Widget _getUserAvatar() {
    if (!_isUserLoggedIn()) {
      // 未登录用户显示默认图标
      return Container(
        width: 40.w,
        height: 40.w,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: Colors.grey[600],
        ),
        child: Icon(Icons.person, color: Colors.white, size: 24.w).center(),
      );
    }

    final currentUser = _userManager.getCurrentUser();
    if (currentUser != null) {
      // 已登录用户显示头像
      return Container(
        width: 40.w,
        height: 40.w,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          border: Border.all(color: Colors.white.withOpacity(0.2), width: 1),
        ),
        child: ClipOval(
          child: Image.asset(
            currentUser.profileImage,
            width: 40.w,
            height: 40.w,
            fit: BoxFit.cover,
            errorBuilder: (context, error, stackTrace) {
              return Container(
                width: 40.w,
                height: 40.w,
                color: Colors.grey[600],
                child:
                    Icon(
                      Icons.person,
                      color: Colors.white,
                      size: 24.w,
                    ).center(),
              );
            },
          ),
        ),
      );
    }

    // 用户没有头像时显示默认图标
    return Container(
      width: 40.w,
      height: 40.w,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        color: Colors.grey[600],
      ),
      child: Icon(Icons.person, color: Colors.white, size: 24.w).center(),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/my_background.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部导航栏
              _buildTopNavigationBar(),

              // 聊天消息列表
              Expanded(child: _buildMessagesList()),

              // 输入区域
              _buildInputArea(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopNavigationBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          // 返回按钮
          Icon(Icons.arrow_back_ios, color: Colors.white, size: 20.w).inkWell(
            onTap: () {
              Navigator.pop(context);
            },
          ),

          SizedBox(width: 12.w),

          // AI头像
          Container(
            width: 40.w,
            height: 40.w,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(
                color: Colors.white.withOpacity(0.2),
                width: 1,
              ),
            ),
            child: ClipOval(
              child: Image.asset(
                'assets/images/ai.png',
                width: 40.w,
                height: 40.w,
                fit: BoxFit.cover,
              ),
            ),
          ),

          SizedBox(width: 12.w),

          // AI名称
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('AI Assistant')
                    .fontSize(16.sp)
                    .textColor(Colors.white)
                    .fontFamily(
                      GoogleFonts.poppins(
                        fontWeight: FontWeight.w600,
                      ).fontFamily!,
                    ),
                Text('Online').fontSize(12.sp).textColor(Colors.grey[400]),
              ],
            ),
          ),

          // 举报
          Image.asset(
            'assets/images/report.png',
            width: 24.w,
            height: 24.w,
          ).inkWell(
            onTap: () {
              _handleAIChatReport();
            },
          ),
        ],
      ),
    );
  }

  /// 构建消息列表
  Widget _buildMessagesList() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: ListView.builder(
        controller: _scrollController,
        itemCount: _messages.length + (_isLoading ? 1 : 0),
        itemBuilder: (context, index) {
          if (index == _messages.length && _isLoading) {
            // 显示加载指示器
            return _buildLoadingIndicator();
          }

          final message = _messages[index];
          return _buildMessageItem(message);
        },
      ),
    );
  }

  /// 构建加载指示器
  Widget _buildLoadingIndicator() {
    return Container(
      margin: EdgeInsets.only(bottom: 16.h),
      child: Row(
        children: [
          // AI头像
          Container(
            width: 32.w,
            height: 32.w,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(
                color: Colors.white.withOpacity(0.2),
                width: 1,
              ),
            ),
            child: ClipOval(
              child: Image.asset(
                'assets/images/ai.png',
                width: 32.w,
                height: 32.w,
                fit: BoxFit.cover,
              ),
            ),
          ),

          SizedBox(width: 12.w),

          // 加载动画
          Container(
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
            decoration: BoxDecoration(
              color: Colors.grey[800],
              borderRadius: BorderRadius.circular(18.r),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                SizedBox(
                  width: 16.w,
                  height: 16.w,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                  ),
                ),
                SizedBox(width: 8.w),
                Text('AI is typing...').fontSize(14.sp).textColor(Colors.white),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建消息项
  Widget _buildMessageItem(AIChatMessage message) {
    return Container(
      margin: EdgeInsets.only(bottom: 16.h),
      child: Row(
        mainAxisAlignment:
            message.isUser ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (!message.isUser) ...[
            // AI头像
            Container(
              width: 32.w,
              height: 32.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(
                  color: Colors.white.withOpacity(0.2),
                  width: 1,
                ),
              ),
              child: ClipOval(
                child: Image.asset(
                  'assets/images/ai.png',
                  width: 32.w,
                  height: 32.w,
                  fit: BoxFit.cover,
                ),
              ),
            ),
            SizedBox(width: 12.w),
          ],

          // 消息内容
          Flexible(
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
              decoration: BoxDecoration(
                color: message.isUser ? Colors.blue[600] : Colors.grey[800],
                borderRadius: BorderRadius.circular(18.r),
              ),
              child: Text(
                message.content,
              ).fontSize(14.sp).textColor(Colors.white),
            ),
          ),

          if (message.isUser) ...[
            SizedBox(width: 12.w),
            // 用户头像
            _getUserAvatar(),
          ],
        ],
      ),
    );
  }

  /// 构建输入区域
  Widget _buildInputArea() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(color: Colors.transparent),
      child: Container(
        height: 50.h,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(25.r),
        ),
        child: Row(
          children: [
            // 输入框
            Expanded(
              child: TextField(
                controller: _messageController,
                style: TextStyle(color: Colors.black, fontSize: 14.sp),
                decoration: InputDecoration(
                  hintText: 'Type a message...',
                  hintStyle: TextStyle(
                    color: Colors.grey[500],
                    fontSize: 14.sp,
                  ),
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: 20.w,
                    vertical: 0.h,
                  ),
                  isDense: true,
                ),
                textAlignVertical: TextAlignVertical.center,
                onSubmitted: (value) {
                  if (value.trim().isNotEmpty) {
                    _sendMessage(value.trim());
                    _messageController.clear();
                  }
                },
              ),
            ),

            // 发送按钮
            Padding(
              padding: EdgeInsets.only(right: 8.w),
              child: Image.asset(
                'assets/images/send_answer.png',
                width: 24.w,
                height: 24.w,
              ).inkWell(
                onTap: () {
                  final content = _messageController.text.trim();
                  if (content.isNotEmpty) {
                    _sendMessage(content);
                    _messageController.clear();
                  }
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 处理AI聊天举报
  void _handleAIChatReport() {
    showVamosReportDialog(
      context: context,
      title: 'Report AI Chat',
      subtitle: 'Please select a reason for reporting this AI conversation.',
      onReportSubmitted: (VamosReportOption option) {
        _handleAIChatReportSuccess();
      },
    );
  }

  /// 处理AI聊天举报成功
  void _handleAIChatReportSuccess() {
    // 显示举报成功提示
    NotificationUtils.showSuccess(
      context,
      message: 'Report submitted successfully.',
    );

    Navigator.pop(context);
  }
}

/// AI聊天消息数据模型
class AIChatMessage {
  final String id;
  final String content;
  final bool isUser;
  final DateTime timestamp;

  AIChatMessage({
    required this.id,
    required this.content,
    required this.isUser,
    required this.timestamp,
  });
}
